<template>
  <div class="login-box">
      <div class="login-form">
          <el-input
            v-model="username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
        />
        <el-input
            v-model="email"
            placeholder="请输入邮箱"
            prefix-icon="el-icon-message"
        />
        <el-input
            v-model="password"
            show-password
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
        />
        <el-input
            v-model="rePassword"
            show-password
            placeholder="请输入密码确认"
            prefix-icon="el-icon-lock"
        />
        <el-button class="register-btn" @click="register" type="success" round>注册</el-button>
      </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
    data() {
        return {
            username: '',
            password: '',
            rePassword: '',
            email: '',
        };
    },
    methods: {
        register() {
            const { username = '', email = '', password = '', rePassword = '' } = this;
            if (username === '') {
                this.$message.error('用户名不能为空');
                return;
            }
            if (email === '') {
                this.$message.error('邮箱不能为空');
                return;
            }
            if (password === '') {
                this.$message.error('密码不能为空');
                return;
            }
            if (password !== rePassword) {
                this.$message.error('两次密码不能相同');
                return;
            }
            axios({
                method: 'POST',
                url: '/api/register',
                data: {
                    username,
                    password,
                    email,
                },
            }).then((res) => {
                const { data } = res;
                if (Number(data.code) === 0) {
                    const { data: successData } = data;
                    this.$message({
                        message: successData.msg,
                        type: 'success',
                    });
                    setTimeout(() => {
                        this.$router.push({
                            path: '/login',
                        });
                    }, 1000);
                } else {
                    this.$message.error(data.msg);
                }
            });
        }
    }
}
</script>

<style lang="less" scoped>
.login-box {
    position: relative;
    height: 100%;
    .login-form {
        width: 320px;
        display: inline-block;
        position: absolute;
        left: 0;
        right: 0;
        top: 50%;
        margin: auto;
        border: solid 1px #999;
        padding: 64px 64px;
        transform: translateY(-50%);
        /deep/ .el-input {
            margin: 12px 0;
        }
        /deep/ .register-btn {
            width: 100%;
            margin-top: 24px;
        }
    }
}
</style>